<?php

namespace App\Jobs\Stats\Settlement\Elasticsearch;

use App\Jobs\Stats\Stats as JobStats;
use App\Jobs\Stats\Traits\DatabaseElasticsearch;
use App\Models\Admin\Stats\Settlement\Game as Stats;
use App\Models\Elasticsearch\Settlement\Info;
use App\Core\Traits\Numeral;

class Game extends JobStats
{
    use Numeral, DatabaseElasticsearch;

    /**
     * 执行统计任务。
     *
     * @return void
     */
    public function stats()
    {
        $params = ['body' => ['size' => 0, 'track_total_hits' => false]];
        // 筛选【状态】
        $this->makeWhere($params, 'status', Info::STATUS_NORMAL);
        // 筛选【类型】
        $this->makeWhere($params, 'player_type', Info::PLAYER_TYPE);
        // 筛选【时间】
        $this->makeWhereDatetime($params, 'end_time', [$this->task->timed, $this->task->timed + 86400], Info::INDEX_NAME);
        // 筛选【平台】
        $this->makeWhere($params, 'plat_code', $this->task->plat_code);
        // 筛选【游戏】
        $this->makeWhere($params, 'game_id', $this->task->game_id);

        // 统计参数
        $params['body']['aggs'] = $this->makeGroup(['currency'], array_merge(
            $this->makeAggs('sum', [
                'bet_base', 'bet_num', 'gain_player',
                'usd.bet_base', 'usd.bet_num', 'usd.gain_player'
            ]),
            $this->makeDistinct('uid')
        ));
        // 查询数据
        $results = Info::search($params);

        // 保存数据
        foreach ($results['aggregations']['group']['buckets'] as $item) {
            Stats::updateOrCreate(
                $this->task->only(['timed', 'plat_code', 'game_id']) + $item['key'],
                [
                    'doc_count' => $item['doc_count'], 'player_count' => $item['distinct_uid']['value'],
                    'bet_base' => $item['bet_base']['value'], 'bet_num' => $item['bet_num']['value'],
                    'gain_player' => $item['gain_player']['value'], 'amount' => -$item['gain_player']['value'],
                    'usd' => [
                        'bet_base' => $this->makeRound($item['usd.bet_base']['value']),
                        'bet_num' => $this->makeRound($item['usd.bet_num']['value']),
                        'gain_player' => $this->makeRound($item['usd.gain_player']['value']),
                        'amount' => $this->makeRound(-$item['usd.gain_player']['value']),
                    ],
                    'rtp' => $this->makeRtp($item['bet_num']['value'], $item['gain_player']['value']),
                ]
            );
        }
    }
}
